import asyncio
import aiohttp
import csv
import time
import random
import json
import execjs

# 原始的 hotel id 列表
id_list = [
    105694250, 105694078, 105726881, 98999479, 106210175, 106225883, 106244754,
]


# 定义异步请求函数
async def fetch_price(session, id):
    headers = {}  # 根据实际需求填写
    cookies = {}  # 根据实际需求填写
    data = {}  # 根据实际需求填写
    params = {}  # 根据实际需求填写

    # 获取代理服务器
    proxy_response = await session.get(
        'https://share.proxy.qg.net/get?key=C2695231&num=1&area=&isp=0&format=json&distinct=false'
    )
    proxy_data = await proxy_response.json()
    print(proxy_data)
    proxyAddr = proxy_data['data'][0]['server']

    # 设置代理
    authKey = "C2695231"
    password = "C9928A3124C7"
    proxyUrl = f"http://{authKey}:{password}@{proxyAddr}"
    proxies = {
        "http": proxyUrl,
        "https": proxyUrl,
    }

    # 发送请求获取酒店数据
    url = "https://m.ctrip.com/restapi/soa2/21881/json/getHotelScript"
    async with session.post(url, headers=headers, cookies=cookies, data=data, proxy=proxyUrl) as response:
        response_json = await response.json()
        Response = response_json['Response']
        code = Response.split('window')[1][1:].replace(');})();', '')
        print(code)

        # 使用 execjs 解析 JS 代码
        with open('酒店testab.js', 'r', encoding='utf8') as f:
            demo = f.read().replace("'data'", code)
        testab = execjs.compile(demo).call('testab', code)
        print(testab)

        # 获取房价数据
        url = "https://m.ctrip.com/restapi/soa2/21881/json/rateplan"
        async with session.post(url, headers=headers, cookies=cookies, params=params,
                                data=json.dumps(data, separators=(',', ':')), proxy=proxyUrl) as response:
            response_json = await response.json()
            datas = response_json['Response']['baseRooms']

            # 保存数据到 CSV
            with open('价格3.csv', 'a', newline='', encoding='utf-8') as f:
                writer = csv.writer(f)
                for rooms in datas:
                    price = rooms['saleRoom'][0]['money']['price']
                    roomName = rooms['baseRoom']['roomName']
                    writer.writerow([str(id), roomName, price])
                    print(id, roomName, price)

    await asyncio.sleep(random.uniform(1, 3))  # 随机睡眠模拟延迟


# 异步调用所有任务
async def main():
    async with aiohttp.ClientSession() as session:
        tasks = []
        for id in id_list:
            tasks.append(fetch_price(session, id))
        await asyncio.gather(*tasks)


if __name__ == "__main__":
    # 写入CSV文件表头
    with open('价格3.csv', 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['酒店ID', '房间名称', '价格'])

    # 运行异步任务
    asyncio.run(main())


